﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using TaskKernel.DTO;

namespace TaskWebApplicationUI
{
    public partial class SortField : UserControl
    {
        private const string sortingFieldControlName = "SortingField";
        private const string sortingCookie = "SortingFieldCookie";
        private const string sortDirectionControlName = "SortDirection";

        public IEnumerable<SortingField> SortingFields
        {
            set { ViewState[sortingFieldControlName] = value; }
            get
            {
                return ViewState[sortingFieldControlName] != null
                           ? (IEnumerable<SortingField>) ViewState[sortingFieldControlName]
                           : Enumerable.Empty<SortingField>();
            }
        }

        public Queue<AbstractSortField> SortingFieldsCookie
        {
            set { ViewState[sortingCookie] = value; }
            get
            {
                return ViewState[sortingCookie] != null
                           ? (Queue<AbstractSortField>) ViewState[sortingCookie]
                           : new Queue<AbstractSortField>();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            IEnumerable<DropDownList> dynamicListSortingFields = CreateControlsFromSortingFields(SortingFields,
                                                                                                 new Queue
                                                                                                     <AbstractSortField>
                                                                                                     (SortingFieldsCookie));
            IEnumerable<RadioButtonList> dynamicListSortDirections = CreateControlsFromSortDirections(SortingFields,
                                                                                                      new Queue
                                                                                                          <
                                                                                                          AbstractSortField
                                                                                                          >(
                                                                                                          SortingFieldsCookie));
            AddControlsListToPage(dynamicListSortingFields, dynamicListSortDirections);
        }

        private void AddControlsListToPage(IEnumerable<DropDownList> dynamicDdlList,
                                           IEnumerable<RadioButtonList> dynamicRbList)
        {
            PlaceHolder1.Controls.Add(new LiteralControl("<table><tr>"));
            foreach (DropDownList dropDownList in dynamicDdlList)
            {
                PlaceHolder1.Controls.Add(new LiteralControl("<td >"));
                PlaceHolder1.Controls.Add(dropDownList);
                PlaceHolder1.Controls.Add(new LiteralControl("</td>"));
            }
            PlaceHolder1.Controls.Add(new LiteralControl("</tr><tr>"));
            foreach (RadioButtonList dropDownList in dynamicRbList)
            {
                PlaceHolder1.Controls.Add(new LiteralControl("<td >"));
                PlaceHolder1.Controls.Add(dropDownList);
                PlaceHolder1.Controls.Add(new LiteralControl("</td>"));
            }
            PlaceHolder1.Controls.Add(new LiteralControl("</tr></table>"));
        }

        public IEnumerable<RadioButtonList> CreateControlsFromSortDirections(IEnumerable<SortingField> sortingFields,
                                                                             Queue<AbstractSortField> abstractSortFields)
        {
            var filteredFields = sortingFields.TakeWhile(x => x.Visible);
            var dynamicRbList = new List<RadioButtonList>();
            for (int i = 0; i < filteredFields.Count() - 1; i++)
            {
                var radioButtonList = new RadioButtonList();
                radioButtonList.CssClass = "bodyt";
                radioButtonList.DataSource = CreateListDirections();
                radioButtonList.ID = sortDirectionControlName + "_" + i;
                radioButtonList.DataTextField = "Field";
                radioButtonList.DataValueField = "SortDirectionAsc";
                radioButtonList.EnableViewState = true;
                radioButtonList.DataBind();
                var sortDirectionForField = sortingFields.ElementAt(i).SortDirectionAsc;
                radioButtonList.SelectedValue = sortDirectionForField.ToString();
                if (abstractSortFields.Any())
                    radioButtonList.SelectedValue = abstractSortFields.Dequeue().SortDirectionAsc.ToString();
                dynamicRbList.Add(radioButtonList);
            }
            return dynamicRbList;
        }

        private IEnumerable<AbstractSortField> CreateListDirections()
        {
            return new List<AbstractSortField>
                       {new AbstractSortField("По возрастанию", true), new AbstractSortField("По убыванию", false)};
        }

        public IEnumerable<DropDownList> CreateControlsFromSortingFields(IEnumerable<SortingField> sortingFields,
                                                                         Queue<AbstractSortField> abstractSortFields)
        {
            var filteredFields = sortingFields.TakeWhile(x => x.Visible);
            var dynamicDdlList = new List<DropDownList>();
            for (int i = 0; i < filteredFields.Count() - 1; i++)
            {
                var dynamicDDL = new DropDownList();
                dynamicDDL.CssClass = "bodyt";
                dynamicDDL.DataSource = filteredFields;
                dynamicDDL.ID = sortingFieldControlName + "_" + i;
                dynamicDDL.DataTextField = "Description";
                dynamicDDL.DataValueField = "Field";
                dynamicDDL.EnableViewState = true;
                dynamicDDL.DataBind();
                if (abstractSortFields.Any())
                    dynamicDDL.SelectedValue = abstractSortFields.Dequeue().Field;
                dynamicDdlList.Add(dynamicDDL);
            }
            return dynamicDdlList;
        }

        public Queue<AbstractSortField> GetQueueForSort()
        {
            var queue = new Queue<AbstractSortField>();
            for (int i = 0; i < SortingFields.Count() - 1; i++)
            {
                var control = (DropDownList) PlaceHolder1.FindControlRecursive(sortingFieldControlName + "_" + i);
                if (!String.IsNullOrEmpty(control.SelectedItem.Value))
                {
                    var control2 =
                        (RadioButtonList) PlaceHolder1.FindControlRecursive(sortDirectionControlName + "_" + i);
                    bool direction = bool.Parse(control2.SelectedItem.Value);
                    string expr = control.SelectedItem.Value;
                    var sortField = new AbstractSortField(expr, direction);
                    if (!queue.Contains(sortField))
                        queue.Enqueue(sortField);
                }
            }
            return queue;
        }
    }
}